// /src/store/index.ts
import { defineStore } from 'pinia'
import { RouteRecordRaw } from 'vue-router'

// pinia状态管理器
export const useRouterStore = defineStore('star_router', {
  state: () => {
    return {
      // 路由表
      routes: [] as Array<RouteRecordRaw>
    }
  },
  getters: {},
  actions: {
    async RESET_STATE () {
      this.$reset()
    },
    // 添加动态路由，并同步到状态管理器中，这个地方逻辑是写的最简单的方式，大家可以根据自己的业务需求来改写，本质就是使用addRoute来实现
    addRoutes (data: Array<any>, router: any) {
      this.routes = this.generateRouter(data)
      console.log('this.routes', this.routes)
      this.routes.forEach(m => router.addRoute(m))
    },
    generateRouter (userRouters: Array<any>) {
      let newRouters = [] as Array<RouteRecordRaw>
      newRouters = userRouters.map(r => {
        const routes = {
          path: r.path,
          name: r.name,
          component: () => import(`@/views/${r.component}`),
          redirect: r.redirect,
          meta: {
            title: r.title
          },
          children: [] as Array<RouteRecordRaw>
        }
        if (r.children && r.children.length > 0) {
          routes.children = this.generateRouter(r.children)
        }
        return routes
      })
      return newRouters
    }
  },
  persist: false
})

export default useRouterStore
